import sys
import os
import shutil

Import("env")

# Install GitPython for interacting with remote repositories
try:
    import git
except ImportError:
    env.Execute("$PYTHONEXE -m pip install GitPython")
    import git

################################# BUILD MACROS #################################

# For each microcontroller, select the corresponding rtthread-nano port folder:
devices = {
    "STM32F0": "cortex-m0",
    "STM32F1": "cortex-m3",
    "STM32F2": "cortex-m3",
    "STM32F3": "cortex-m4",
    "STM32F4": "cortex-m4",
}

port = []
rtthread_nano_tag = ""
tag_name = ""

# Check all definitions and try to find matching macro/definition:
for item in env.get("CPPDEFINES", []):
    if isinstance(item, tuple):
        if item[0] in devices:
            port.append(item[0])
        # Look for special tags while parsing the macros
        elif item[0] == "rtthread-nano_TAG":
            rtthread_nano_tag = item[1]
    else:
        if item in devices:
            port.append(item)


# Throw exception if no macros match a device name:
if len(port) == 0:
    sys.stderr.write(
        "Error: No device defined for rtthread-nano! Please provide platform manually - options below:\n"
    )
    device_keys = devices.keys()
    s = " ,".join(device_keys)
    sys.stderr.write(str(s) + "\n")
    env.Exit(1)
# Else, add the appropriate port folders to the include path and source filter:
else:
    if len(port) > 1:
        sys.stderr.write(
            "Warning: Multiple devices defined: %s\n Using %s as default device.\n"
            % (" ".join(port), port[0])
        )
    print("PlatformIO-rtthread-nano: building for", port[0])
    env.Append(CPPPATH=[os.path.realpath("include")])
    env.Append(CPPPATH=[os.path.realpath(os.path.join("libcpu/arm", devices[port[0]]))])

    env.Replace(
        SRC_FILTER=[
            "-<bsp>",
            "+<src>",
            os.path.join("+<libcpu/arm", devices[port[0]], "context_gcc.S>"),
            os.path.join("+<libcpu/arm", devices[port[0]], "*.c>"),
        ]
    )

    # rtthread-nanoConfig.h is located in the project space, outside of the lib:
    env.Append(CPPPATH=env.get("PROJECT_INCLUDE_DIR", []))

    # print(env.get("SRC_FILTER"))
    # print(env.get("CPPPATH"))
    # print(env.get("PROJECT_INCLUDE_DIR"))

    
